package com.bw.service.impl;


import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.bw.entity.AssetInfo;
import com.bw.entity.Dict;
import com.bw.mapper.AssetsMapper;
import com.bw.service.AssetsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class AssetsServiceImpl implements AssetsService {

    @Autowired
    AssetsMapper assetsMapper;

    @Override
    public AssetInfo add(AssetInfo assetInfo) {

        //表单非空校验，“*”非空字段
        Integer typeId = assetInfo.getTypeId();
        if (typeId == null) {
            throw new RuntimeException("资产类型必填");
        }
        String name = assetInfo.getName();
        Assert.notBlank(name, "资产名称必填"); // string类型用 notblank
        // 断言（断定，认为） 断定第一个入参不是null， 如果是null，则抛出异常
        Assert.notNull(assetInfo.getSourceId(), "资产来源必填");
        Assert.notBlank(assetInfo.getCreateTime(), "日期必填");
        Assert.notBlank(assetInfo.getPrice(), "价格必填");

        //资产编号唯一性校验 ,不能重复
        AssetInfo assetInfoDB = assetsMapper.selectByNum(assetInfo.getNum());

        if (assetInfoDB != null) {
            throw new RuntimeException("资产编号重复！");
        }

        //购入价格校验，必须为数值类型
        String price = assetInfo.getPrice();
        boolean number = NumberUtil.isNumber(price);
        if (number == false) {
            throw new RuntimeException("价格必须为数值类型 ！");
        }
        //控制打印方法参数
        System.out.println("打印方法参数" + JSON.toJSONString(assetInfo));
        // 添加成功， 返回资产对象
        assetsMapper.add(assetInfo);


        return assetInfo;
    }


    @Override
    public AssetInfo selectByNum(String num) {

        AssetInfo assetInfoDB = assetsMapper.selectByNum(num); // 查询需要修改的这条数据
        List<Dict> sourceList = assetsMapper.selectSourceList(); // 查询 下拉框所有的数据  为了让用户切换
        assetInfoDB.setSourceList(sourceList);

        List<Dict> typeList = assetsMapper.selectTypeList();
        assetInfoDB.setTypeList(typeList);
        return assetInfoDB;
    }
}
